import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/pages/home/index.dart';
import 'package:flutter_enjoy_plus/pages/mine/index.dart';
import 'package:flutter_enjoy_plus/utils/EvenBus.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  List tabsList = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png'
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png'
    }
  ];
  int activeIndex = 0;

  // 切换tabs
  void updateActiveIndex(int index) {
    setState(() {
      activeIndex = index;
    });
  }

  // 方案1 使用函数加分支 加载内容
  // getTabsContent() {
  //   if (activeIndex == 0) {
  //     return const HomePage();
  //   } else if (activeIndex == 1) {
  //     return const MinePage();
  //   } else {
  //     return Container();
  //   }
  // }

  // 方案2 使用 IndexedStack 实现，性能更高

  // 获取底部导航栏项
  List<BottomNavigationBarItem> getBottomNavigationBarItem() {
    List<BottomNavigationBarItem> list = [];
    for (var item in tabsList) {
      list.add(BottomNavigationBarItem(
          icon: Image.asset(item['icon'], width: 30, height: 30),
          activeIcon: Image.asset(item['activeIcon'], width: 30, height: 30),
          label: item['label']));
    }
    return list;
  }

  @override
  void initState() {
    super.initState();
    tokenManager.init();
    // 监听登出事件 -- 必须加泛型，监听特定的事件
    eventBus.on<LogoutEvent>().listen((event) {
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: IndexedStack(
        index: activeIndex,
        children: [
          const HomePage(),
          MinePage(
              activeIndex: activeIndex, updateActiveIndex: updateActiveIndex)
        ],
      )),
      // 底部导航栏
      bottomNavigationBar: BottomNavigationBar(
        items: getBottomNavigationBarItem(),
        type: BottomNavigationBarType.fixed,
        currentIndex: activeIndex,
        onTap: (index) {
          setState(() {
            activeIndex = index;
          });
        },
        selectedItemColor: const Color.fromRGBO(106, 158, 189, 1),
        unselectedItemColor: Colors.black,
      ),
    );
  }
}
